package com.aaa.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.aaa.utils.JWTUtils;
import com.aaa.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * Ordered设置优先级
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getPath().toString();
        //1、判断是否请求登录
        if ("/login".equals(path)){
            return chain.filter(exchange);
        }

        //2、如果已经登录，验证token
        String token = request.getHeaders().getFirst("token");
        //token不为空   token正确   token未过期
        if (StringUtils.hasText(token) && JWTUtils.validateToken(token) && redisTemplate.hasKey(token)){
            //因为还在经过网关发送请求，代表还在操作，所以token刷新过期时间
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
            return chain.filter(exchange);
        }

       //3、封装返回数据
        Result<String> result = new Result<>(401,"请先登录",null);

        //将数据转为json格式
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
